<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var deadLoopCatch = function(argument, runFnName, deadLoopTimeLimit = 5000) {
            let fnName;
            if (runFnName) {
                fnName = runFnName;
            } else {
                let str = argument.callee.toString();
                var re = /^function\s*(\w+)\(/ig;
                var matches = re.exec(str);
                if (matches && matches[1]) {
                    fnName = matches[1];
                } else {
                    //如果是匿名函数，且用户没有传递第二个参数的时候，警告
                    console.warn("When the loop is an anonymous function, please pass the second parameter for function deadLoopCatch")
                    fnName = "---UMKNOW--";
                }


            }
            //初始化开始时间和结束时间
            let startTime = endTime = new Date().getTime();
            let result = {
                fnName,
                _startTime: startTime,
                _endTime: endTime,
                _deadLoopTimeLimit: deadLoopTimeLimit,
                updateTime: () => {
                    result._endTime = new Date().getTime();

                },
                isDeadLoop: () => {
                    let isDeadLoop = result._endTime - result._startTime >= result._deadLoopTimeLimit;
                    //这代码好像有一点弊端，如果这里不执行的话，还是会死循环
                    console.log("deadLoopCatch:result._endTime - result._startTime", result._endTime - result._startTime)
                    if (isDeadLoop) {
                        console.error(`Function ${fnName} triggered an endless loop!`)
                    }
                    return isDeadLoop;

                }
            }
            return result;
        }

        var abc = function(a, b, c) {
            var i = 1;
            let deadLoopCatchInit = deadLoopCatch(arguments, "abc");
            while (true) {
                deadLoopCatchInit.updateTime()
                if (deadLoopCatchInit.isDeadLoop()) {
                    console.warn("强制中断", deadLoopCatchInit)

                    break;
                }
                console.log("执行中....")
            }
        }
        abc()
    </script>
</body>

</html>